package com.weharvest.edu.utlis;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class CookieUtil {

    public static void set(HttpServletResponse response,String key ,String value,int maxAge){
        Cookie  cookie=new Cookie(key,value);
        cookie.setMaxAge(maxAge);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    /**
     * 返回cookie集
     * @param request
     * @return
     */
    private static   Map<String,Cookie> getCookieMap(HttpServletRequest request){
        Map<String,Cookie> map=new HashMap<>();
        Cookie[] cookies=request.getCookies();
        for(Cookie cookie:cookies){
            map.put(cookie.getName(),cookie);
        }
        return map;
    }

    public static Cookie get(HttpServletRequest request,String key ){
        Map<String,Cookie>cookieMap=getCookieMap(request);
        if(cookieMap.containsKey(key)){
            return cookieMap.get(key);
        }
        return null;
    }

}
